package util.webSearch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedList;

import org.json.JSONArray; // JSON library from http://www.json.org/java/
import org.json.JSONObject;

import util.parser.DeliciousURLInfoPost;
import util.parser.JsonParser;

public class GoogleQuery {

	// Put your website here
	private static final String HTTP_REFERER = "http://www.example11.com/";

	public static LinkedList<WebResult> googleQuery(String query, int results) {

		int r = results;

		LinkedList<WebResult> res = new LinkedList<WebResult>();

		int index = 0;
		while (r >= 0) {
			makeQuery(query, index, results, res);
			index += 8;
			r -= 8;
		}

		return res;
	}

	private static void makeQuery(String query, int showFromRankedesult,
			int limit, LinkedList<WebResult> results) {

		
		//System.out.println(showFromRankedesult + "\t" + limit);
		try {
			// Convert spaces to +, etc. to make a valid URL
			query = URLEncoder.encode(query, "UTF-8");

			URL url = new URL(
					"http://ajax.googleapis.com/ajax/services/search/web?start="
							+ String.valueOf(showFromRankedesult)
							+ "&rsz=large&v=1.0&q=" + query);
			URLConnection connection = url.openConnection();
			connection.addRequestProperty("Referer", HTTP_REFERER);

			// Get the JSON response
			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			String response = builder.toString();
			JSONObject json = new JSONObject(response);

			JSONArray ja = json.getJSONObject("responseData").getJSONArray(
					"results");

			for (int i = 0; i < ja.length() && results.size() < limit; i++) {

				JSONObject j = ja.getJSONObject(i);

				WebResult result = new WebResult();
				result.setSnippet(j.getString("content"));
				result.setTitle(j.getString("titleNoFormatting"));
				result.setUrl(j.getString("url"));
				
				//get delicious data for webresult
				DeliciousURLInfoPost del =  JsonParser.parseDeliciousInfoFromURL(j.getString("url").trim());
				result.setDelicious(del);
				result.setRank(i+1);
				result.setEngine(WebResult.GOOGLE);

				results.add(result);
			}
		} catch (Exception e) {
			System.err.println("Something went wrong...");
			e.printStackTrace();
		}
	}

	public static void makeQuery(String query) {

		System.out.println("\nQuerying for " + query);

		try {
			// Convert spaces to +, etc. to make a valid URL
			query = URLEncoder.encode(query, "UTF-8");

			URL url = new URL(
					"http://ajax.googleapis.com/ajax/services/search/web?start=8&rsz=large&v=1.0&q="
							+ query);
			URLConnection connection = url.openConnection();
			connection.addRequestProperty("Referer", HTTP_REFERER);

			// Get the JSON response
			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			String response = builder.toString();
			JSONObject json = new JSONObject(response);

			System.out.println("Total results = "
					+ json.getJSONObject("responseData")
							.getJSONObject("cursor").getString(
									"estimatedResultCount"));

			JSONArray ja = json.getJSONObject("responseData").getJSONArray(
					"results");

			System.out.println("\nResults:");
			for (int i = 0; i < ja.length(); i++) {
				System.out.print((i + 1) + ". ");
				JSONObject j = ja.getJSONObject(i);
				System.out.println(j.getString("titleNoFormatting"));
				System.out.println(j.getString("url"));
				System.out.println(j.getString("content"));
			}
		} catch (Exception e) {
			System.err.println("Something went wrong...");
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		System.out.println(googleQuery("dinosaurs for kids", 15).size());
	}
}